package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.ydd.common.R;
import com.itheima.ydd.dto.BaseInfoDto;
import com.itheima.ydd.pojo.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class IndexServiceImpl implements IndexService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private YddCateService yddCateService;

    @Autowired
    private YddAdvposService yddAdvposService;

    @Autowired
    private YddTagService yddTagService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private YddArticleService yddArticleService;

    @Autowired
    private YddAdvimgService yddAdvimgService;

    @Autowired
    private YddUserService yddUserService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private SysMenuService sysMenuService;
    //角色和菜单的对应表
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 主页信息统计
     *
     * @return
     */
    @Override
    public ResponseEntity<R<BaseInfoDto>> baseInfo() {
        //所有分类数据
        //yddcate包含id cataname
        List<YddCate> list = yddCateService.list();
        //创建一个allCate list集合
        List<AllCate> cateList = new ArrayList<>();
        //不同分类下的文章数量 --ydd_ article
        QueryWrapper<YddArticle> qw1 = new QueryWrapper<YddArticle>();
        qw1.select("cateid", "count(*) as nums");
        qw1.groupBy("cateid");
        List<Map<String, Object>> articleMaps = yddArticleService.listMaps(qw1);
        //这就是个嵌套循环来赋值
        for (int i = 0; i < list.size(); i++) {
            YddCate yddCate = list.get(i);
            for (int j = 0; j < articleMaps.size(); j++) {
                Map<String, Object> stringObjectMap = articleMaps.get(j);
                if (stringObjectMap.get("cateid") == yddCate.getId()) {
                    Long nums = (Long) stringObjectMap.get("nums");
                    Integer num = nums.intValue();
                    AllCate allCate = new AllCate();
                    allCate.setId(yddCate.getId());
                    allCate.setCatename(yddCate.getCatename());
                    allCate.setNum(num);
                    cateList.add(allCate);
                    break;
                }
            }
        }


        //查询广告位总数
        Integer advposCount = yddAdvposService.count();

        //标签总数
        Integer tagCount = yddTagService.count();

        //管理员用户
        Integer sysUserCount = sysUserService.count();

        //文章总数
        Integer articleCount = yddArticleService.count();

        //分类总数
        Integer cateCount = yddCateService.count();

        //广告图总数
        Integer advimgCount = yddAdvimgService.count();

        //最新用户数据
        //1.查询到所有用户数据
        List<YddUser> userList = yddUserService.list();
        //2.创建一个集合用于保存新用户数据
        List<YddUser> newUserList = new ArrayList<>();
        //3.获取到最新注册的用户数据 --7位
        for (int i = userList.size() - 1; i > userList.size() - 8; i--) {
            newUserList.add(userList.get(i));
        }


        //获取热门文章数据
        //1.获取所有文章数据,根据click倒序排列
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(YddArticle::getClick);
        List<YddArticle> articleList = yddArticleService.list(lqw);
        //2.创建一个集合用于保存热门文章
        List<YddArticle> hotArticleList = new ArrayList<>();
        //3.获取到最新的热门文章数据 7条
        for (int i = 0; i < 7; i++) {
            hotArticleList.add(articleList.get(i));
        }

        //用户数据
        User user = new User();
        //1.用户数量
        Integer total = yddUserService.count();
        user.setTotal(total);
        //2.男女用户数量
        QueryWrapper<YddUser> qw = new QueryWrapper<YddUser>();
        qw.select("sex", "count(*) as nums");
        qw.groupBy("sex");
        List<Map<String, Object>> maps = yddUserService.listMaps(qw);
        for (int i = 0; i < maps.size(); i++) {
            Map<String, Object> stringObjectMap = maps.get(i);
            Integer sex = (Integer) stringObjectMap.get("sex");
            if (sex == 0) {
                Long mNum = (Long) stringObjectMap.get("nums");
                Integer menNum = mNum.intValue();
                user.setUserMan(menNum);
            }
            if (sex == 1) {
                Long wNum = (Long) stringObjectMap.get("nums");
                Integer womanNum = wNum.intValue();
                user.setUserWoman(womanNum);
            }

        }

        //封装返回需要的BaseInfoDto
        BaseInfoDto baseInfoDto = new BaseInfoDto();
        baseInfoDto.setAllCate(cateList);
        baseInfoDto.setAdvposNum(advposCount);
        baseInfoDto.setTagNum(tagCount);
        baseInfoDto.setAdminNum(sysUserCount);
        baseInfoDto.setArticleNum(articleCount);
        baseInfoDto.setCateNum(cateCount);
        baseInfoDto.setAdvimgNum(advimgCount);
        baseInfoDto.setNewUser(newUserList);
        baseInfoDto.setHotArticle(hotArticleList);
        baseInfoDto.setUser(user);

        return ResponseEntity.ok(R.success(baseInfoDto));
    }

    /**
     * 登录
     *
     * @param sysUser
     * @return
     */
    @Override
    public ResponseEntity<R<Map<String, String>>> login(SysUser sysUser) {
        //1.对接收到的密码进行md5加密
        String password = sysUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.根据账号查询用户信息
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getLoginName, sysUser.getLoginName());
        SysUser sysUser1 = sysUserService.getOne(lqw);

        //3.对sysUser1进行判断
        if (ObjectUtils.isEmpty(sysUser1)) {
            return ResponseEntity.ok(R.err("请检查用户名!"));
        }

        //4.校验密码
        if (!StringUtils.pathEquals(password, sysUser1.getPassword())) {
            return ResponseEntity.ok(R.err("密码错误!"));
        }

        //5.对登录用户的状态进行判断
        if (sysUser1.getStatus() != 1) {
            return ResponseEntity.ok(R.err("当前用户被禁用"));
        }
        //6.登录成功,设置token
        String token = AppJwtUtil.getToken(sysUser1.getId());
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return ResponseEntity.ok(R.success(map));
    }

    /**
     * 获取系统配置
     *
     * @return
     */
    @Override
    public ResponseEntity<R<List<SysConfig>>> getConfig() {
        LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysConfig::getTabValue, "system");
        List<SysConfig> list = sysConfigService.list(lqw);
        if (ObjectUtils.isEmpty(list)) {
            return ResponseEntity.ok(R.err("获取系统配置失败"));
        }
        return ResponseEntity.ok(R.success(list));
    }

    @Override
    public ResponseEntity<R<UserManager>> profile(String token) {
        UserManager userManager = new UserManager();
        //获取当前用户的token 里面的id

        Claims claims = AppJwtUtil.tokenToOut(token);
        String id = (String) claims.get("id");
        log.info("token中的id是{}", id);
        //1.根据id进行查询出用户的信息封装到userInfo中
        SysUser byId = sysUserService.getById(id);
        userManager.setUserInfo(byId);

        //2.根据用户的角色id查询出对应的菜单权限
        String roleId = byId.getRoleId();
        //["1c54e003c1fc4dcd9b087ef8d48abac3"]
        String[] roleIds = roleId.replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        //roleId=roleId.substring(2,roleId.lastIndexOf("]")-1);

        log.info(roleIds+"");
        //根据其角色id查询出对应的菜单id集合
        LambdaQueryWrapper<SysRoleMenu> wrapperRAM=new LambdaQueryWrapper<>();
        wrapperRAM.in(SysRoleMenu::getRoleId,roleIds);
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.list(wrapperRAM);
        //根据菜单的id集合查询出id对应的菜单!
        List<String>  menuIds=new ArrayList<>();
        for (SysRoleMenu sysRoleMenu : sysRoleMenus) {
            String menuId = sysRoleMenu.getMenuId();
            menuIds.add(menuId);
        }
        LambdaQueryWrapper<SysMenu> wrapperMenu=new LambdaQueryWrapper<>();
        wrapperMenu.in(ObjectUtils.isEmpty(menuIds),SysMenu::getId,menuIds).eq(SysMenu::getType,1);
        List<SysMenu> sysMenus = sysMenuService.list(wrapperMenu);


        userManager.setMenuList(sysMenus);

        //3.封装dictsList
        HashMap<String, Object> dictsList = new HashMap<>();
        HashMap<String, String> interface_type = new HashMap<>();
        interface_type.put("get", "get");
        interface_type.put("post", "post");
        dictsList.put("interface_type", interface_type);

        ArrayList<String> table_type = new ArrayList<>();
        table_type.add("单表");
        table_type.add("主表");
        table_type.add("附表");
        table_type.add("树结构表");
        dictsList.put("table_type", table_type);

        ArrayList<String> order_type = new ArrayList<>();
        order_type.add("支付宝");
        order_type.add("微信");
        dictsList.put("order_type", order_type);

        ArrayList<String> report_type = new ArrayList<>();
        report_type.add("正常报告");
        report_type.add("异常报告");
        dictsList.put("report_type", report_type);

        HashMap<String, String> theme = new HashMap<>();
        theme.put("ace", "ACE风格");
        dictsList.put("theme", theme);
        userManager.setDictsList(dictsList);
        String [] btnlist=new String[10];
        String s="*";
        btnlist[0]=s;
        userManager.setBtnList(btnlist);
        return ResponseEntity.ok(R.success(userManager));

    }
}
